package com.htlh.normal_broadcast_demo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


    private LocalBroadcastManager localBroadcastManager;
    private LocalReceiver localReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.btn_send_broadcast);
        localBroadcastManager = LocalBroadcastManager.getInstance(this);


        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent("com.htlh.normal_broadcast_demo.MY_BROADCAST");
//                sendBroadcast(intent);
                Intent intent = new Intent("com.htlh.normal_broadcast_demo.LOCAL_BROADCAST");
//                sendOrderedBroadcast(intent,null);
                localBroadcastManager.sendBroadcast(intent);

                IntentFilter intentFilter = new IntentFilter();
                intentFilter.addAction("com.htlh.normal_broadcast_demo.LOCAL_BROADCAST");
                localReceiver = new LocalReceiver();
                localBroadcastManager.registerReceiver(localReceiver,intentFilter);
            }
        });


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(localReceiver);
    }

    class LocalReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context,"local receiver",Toast.LENGTH_SHORT).show();
        }
    }
}
